<template>
  <div>
    <ZgDialog v-model="visible" width="40%" :title="title">
      <a-upload-dragger
        name="file"
        :accept="accept"
        action=""
        @change="onChange"
        :before-upload="beforeUpload"
      >
        <div class="ant-upload-drag-icon">
          <a-icon type="inbox" />
        </div>
        <div class="ant-upload-text">
          <div>将文件拖到此处，或<em>点击上传</em></div>
          <div class="mt10 fs12 error">只能上传xlsx文件，且不超过20MB</div>
        </div>
      </a-upload-dragger>
      <div v-show="uploudResult && uploudResult.length > 0" style="max-height:200px;" class="mt15 pd10 error scroll">
        <div><a-progress class="w120" :percent="percentage"></a-progress></div>
        <div v-for="(msg, index) in uploudResult" :key="index">{{ msg }}</div>
      </div>
      <div slot="footer">
        <a-row>
          <a-col :span="4" class="tal">
            <a-button v-if="uploudResult.length>0" @click="uploudResult=[]">清空消息</a-button>
          </a-col>
          <a-col :span="20">
            <div class="tar">
              <ZgDownloadTmpl :disabled="loading" :fileName="fileName" class="mr10"></ZgDownloadTmpl>
              <a-button :disabled="loading" type="primary" @click="onOk">开始导入</a-button>
            </div>
          </a-col>
        </a-row>
      </div>
    </ZgDialog>
    <div v-if="showBtn" @click="open">
      <slot>
        <ZgButton icon="upload">导入数据</ZgButton>
      </slot>
    </div>
  </div>
</template>

<script>
import storage from 'store'
import {
  ACCESS_TOKEN
} from '@/store/mutation-types'
import WebSocketClient from '@/core/push.js'
import { v4 as uuidv4 } from 'uuid'
import axios from 'axios'
export default {
  props: {
    showBtn: {
      type: Boolean,
      default: true
    },
    title: {
      type: String,
      default: '导入数据'
    },
    fileName: {
      type: String,
      default: ''
    },
    param: {
      type: String,
      default: ''
    },
    url: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      visible: false,
      percentage: 0,
      loading: false,
      accept: '.xlsx',
      uploudResult: [],
      fileList: []
    }
  },
  methods: {
    beforeUpload () {
      return false
    },
    onChange (info) {
      console.log('info:', info)
      this.fileList = info.fileList
    },
    open () {
      this.visible = true
    },
    onOk () {
      if (!this.url || this.url.length === 0) {
        this.$warning({ title: '请设置上传接口！' })
        return
      }
      if (this.fileList.length === 0) {
        this.$warning({ title: '请选择填写好的模板文件进行导入！' })
        return
      }

      this.loading = true
      const timer = setTimeout(() => {
        this.loading = false
      }, 300000)

      const formData = new FormData()
      formData.append('file', this.fileList[0].originFileObj)
      const clientId = uuidv4()
      formData.append('clientId', clientId)
      formData.append('param', this.param)

      const headers = {
        'Content-Type': 'multipart/form-data'
      }
      headers[ACCESS_TOKEN] = storage.get(ACCESS_TOKEN)

      const handler = new WebSocketClient()
      handler.conn(clientId, msg => {
        if (msg.startsWith('percent:')) {
          this.percentage = parseInt(msg.substring(8))
        } else if (msg.startsWith('import:')) {
          this.uploudResult = [msg.substring(7)]
        }
      }, () => {
        axios.post(this.API_URL + this.url, formData, {
          headers: headers
        }).then(res => {
          if (!res.data) {
            this.uploudResult = ['导入方法的返回值不符合格式要求']
          }
          const json = res.data
          this.uploudResult = []
          if (json.code === 1) {
            this.uploudResult = json.data
          } else {
            this.uploudResult = [json.msg]
          }
          clearTimeout(timer)
          this.loading = false
          this.$emit('ok')
          handler.close()
        }).catch(error => {
          clearTimeout(timer)
          this.loading = false
          this.$error({ title: error })
          this.uploudResult = ['导入失败']
          handler.close()
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>
